//
//  SideDemoCtr.swift
//  soapp_Example
//
//  Created by zhu xietong on 2017/10/12.
//  Copyright © 2017年 CocoaPods. All rights reserved.
//

import Foundation
import soapp
import Eelay

private var subNode = "options"
open class GoodsKindsCtr: GesSideController,TableVConfig {
    public var goodsFilter:GoodsFilter = GoodsFilter()
    
    public let tableView = UITableView(frame: [0], style: .plain)
    
    //    var kinds:[[String:Any]] = [
    //        [
    //            "title":"男士",
    //            "cellID":"FirstLever",
    //            "options":[
    //                ["title":"外套"],
    //                ["title":"皮鞋"],
    //                ["title":"商务包"],
    //                ["title":"袜子"],
    //            ]
    //        ],
    //    ]

    
    public var confirmFilter:(GoodsFilter)->Void = {_ in}
    open var kinds:[[String:Any]]{
        get{
            var ks = [[String:Any]]()
            let list1 = DataNode.path(node: "category", mo.model, value: NSMutableArray())
            
            var all = [String:Any]()
            all["id"] = "全部".loc
            all["title"] = "全部".loc
            all["cellID"] = "FirstLever"
            ks.append(all)
            
            list1.list { (dict1:NSMutableDictionary, i1) in
                var lever1 = [String:Any]()
                
                
                var childs1 = [[String:Any]]()
                let list2 = DataNode.path(node: "children", dict1, value: NSMutableArray())
                list2.list({ (dict2:NSMutableDictionary, i2) in
                    var lever2 = [String:Any]()
                    lever2["id"] = dict2["id",""]
                    lever2["title"] = dict2["cat_name",""]
                    lever1["__raw__"] = dict2.rawJson ?? "{}"
                    childs1.append(lever2)
                })
                
                var cat_name = dict1["cat_name",""]
                if cat_name.len < 1{
                    cat_name = dict1["name",""]//积分商城分类名用改字段
                }
                
                
                lever1["id"] = dict1["id",""]
                lever1["title"] = cat_name
                lever1["options"] = childs1
                lever1["__raw__"] = dict1.rawJson ?? "{}"
                lever1["cellID"] = "FirstLever"
                ks.append(lever1)
                
            }
            return ks
        }
    }
    
    public var currendMainKindView = SelectedKindHeader()
    public var currentMainKind:NSMutableDictionary? = nil
    {
        didSet{
            if currentMainKind == nil{
                
                tableView.model <-- ("section1",self.kinds.mutable_array,NodeInsert.arrayRefresh)
                let set = IndexSet(integer:1)
                tableView.reloadSections(set, with: .right)
            }
            else{
                let list = DataNode.path(node: "options",self.currentMainKind, value: NSMutableArray())
                tableView.model <-- ("section1",list,NodeInsert.arrayRefresh)
                let set = IndexSet(integer:1)
                tableView.reloadSections(set, with: .left)
            }
        }
    }
    open var sections:TP.section{
        get{
            let sec:TP.section = [
                [
                    ["cellID":"logo","logo":__logos.one_str,"name":__seller.one_str,"info":__titles.creat_info(6),"__model":mo.model],
                    ],
                [],
                ]
            return sec
        }
    }
    
    
    open var selector:TP.selector{
        get{
            let sel:TP.selector = [
                "cellID<logo>":LogoCell.self,
                "<section1>":Lever2Cell.self,
                "cellID<FirstLever>":Lever1Cell.self,
                ]
            return sel
            
        }
    }
    
    
    
    open func selectLever1Kind(kind:NSMutableDictionary) {
        
        self.goodsFilter.level2 = nil
        self.goodsFilter.level1 = kind["id",""]
        self.confirmFilter(self.goodsFilter)
    }
    open func selectLever2Kind(kind:NSMutableDictionary) {
        self.goodsFilter.level1 = (self.currentMainKind ?? NSMutableDictionary())["id",""]
        self.goodsFilter.level2 = kind["id",""]
        self.confirmFilter(self.goodsFilter)
        
    }
    
    //    var selectLever2Kind:([String:Any])->Void = {_ in}
    
    open override func viewDidLoad() {
        self.side = .left(width: 280.co)
        super.viewDidLoad()
        let line = UIView()
        
        jo_contentView.eelay = [
            [tableView,[ee.T.L.B.R,[30,10,-10,-10]]],
            //            [line,[ee.T.B.R],0.6],
        ]
        
        line.backgroundColor = UIColor.separator_color
        self.configTables(tables: tableView)
        tableView.buildDynamicHeight(height: 201)
        tableView.separatorStyle = .none
        tableView.load(sections: sections, selector: selector)
        tableView.backgroundColor = .clear
        tableView.reloadData()
        
        
        self.currentMainKind = nil
        weak var wself = self
        currendMainKindView.backAction = {
            wself?.currentMainKind = nil
        }
        currendMainKindView.seeAllAction = { data in
            co_delay(delay: 0.1, closure: {
                wself?.close()
                wself?.selectLever1Kind(kind: data)
            })
            
        }
    }
    
    
    open override var backgroundView: UIView{
        let blurView = UIVisualEffectView()
        let sty = UIBlurEffect.Style.extraLight
        let blurEffect = UIBlurEffect(style: sty)
        blurView.effect = blurEffect
        return blurView
    }
    
    
    
    open override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    
    
    
    open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1
        {
            if self.currentMainKind == nil{
                return nil
            }
            else{
                self.currendMainKindView.mo.model = self.currentMainKind!
                return currendMainKindView
            }
        }
        return nil
    }
    
    open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1
        {
            if self.currentMainKind == nil{
                return 0
            }
            else{
                return 56
            }
        }
        return 0
    }
    
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1
        {
            if self.currentMainKind == nil{
                guard let data = tableView.cellData(at: indexPath) else{return}
                let list = DataNode.path(node: "options", data, value: NSMutableArray())
                if list.count < 1{
                    weak var wself = self
                    co_delay(delay: 0.1, closure: {
                        wself?.close()
                        self.selectLever1Kind(kind: data)
                    })
                    return
                }
                self.currentMainKind = data
            }
            else{
                let list = DataNode.path(node: "\(subNode)", self.currentMainKind, value: NSMutableArray())
                list.list({ (dict:NSMutableDictionary, i) in
                    dict["selected"] = "NO"
                })
                guard let data = tableView.cellData(at: indexPath) else{return}
                data["selected"] = "YES"
                tableView.reloadData()
                var params = [String:Any]()
                params["name"] = data["",""]
                
                weak var wself = self
                co_delay(delay: 0.1, closure: {
                    wself?.close()
                    wself?.selectLever2Kind(kind: data)
                })
                
            }
        }
    }
    
    public func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
    }
    
}

extension GoodsKindsCtr{
    
    open class SelectedKindHeader:JoView{
        public let nameBt = UIButton()
        public let allBt = UIButton()
        public var backAction:()->Void = {}
        public var seeAllAction:(NSMutableDictionary)->Void = {_ in}
        open override func addLayoutRules() {
            
            let line = UIView()
            self.eelay = [
                [nameBt,[ee.T.L.B,[34,10,-12]]],
                [line,[ee.L.B.R,[10,0,-10]],"0.6"],
                [allBt,[nameBt,ee.Y],[ee.R,-10]],
            ]
            
            line.backgroundColor = UIColor(shex:"#888")
            _ = nameBt.ui.font(size: 14).ncolor(hex: "#222")
            nameBt.ui.ncolor(hex: "#222").font(size: 16).nimage(UIImage(named:"kind_back"))
            nameBt.addTarget(self, action: #selector(back), for: .touchUpInside)
            nameBt.backgroundColor = .clear
            
            allBt.ui.ntitle(title: "[\("查看".loc)]").ncolor(hex: "#222").font(size: 12)
            allBt.contentEdgeInsets = [10,20]
            allBt.addTarget(self, action: #selector(seeAll), for: .touchUpInside)
        }
        
        @objc func seeAll()
        {
            self.seeAllAction(mo.model)
        }
        
        @objc func back(){
            self.backAction()
        }
        
        override open func mo_model_reload() {
            nameBt.ui.ntitle(title: mo.model["title",""])
        }
        
    }
    
    class LogoCell:JoTableCell
    {
        let logoV = UIImageView()
        let nameL = UILabel()
        let infoL = UILabel()
        let careBt = UIButton()
        override func addLayoutRules() {
            contentView.eelay = [
                [logoV,[ee.T.L.B,[44.co,26,-26]],"\(73.co)",73.co],
                [infoL,[logoV,ee.R,ee.L,10],[ee.R,-30],[logoV,ee.B]],
                [nameL,[logoV,ee.R,ee.L,10],[ee.R,-30],[logoV,ee.T]],
                //                [careBt,[logoV,ee.R,ee.L,10],[ee.R,-30],[infoL,ee.B,ee.T,10]],
            ]
            //            careBt.iconV.image = UIImage(named:"iwe_guanzhu")
            //            careBt.titleL.ui.cl_666.font13.text("233 关注")
            _ = nameL.ui.font17.cl_222
            _ = infoL.ui.font12.cl_666.line(2)
            contentView.backgroundColor = .clear
            self.backgroundColor = .clear
            
        }
        override func mo_model_reload() {
            //            logoV.img_url = mo.model["logo",""]
            //            nameL.text = mo.model["name",""]
            //            infoL.text = mo.model["info",""]
            logoV.img_url = mo.model["__model.thumb",""]
            nameL.text = mo.model["__model.brand_name",""]
            infoL.text = mo.model["__model.desc",""]
        }
    }
    
    class Lever1Cell:JoTableCell{
        let titleL = UILabel()
        override func addLayoutRules() {
            contentView.eelay = [
                [titleL,[ee.T.L.B.R,[20,16,-20,-16]],"20"],
                [__line,[ee.L.B.R,[16,0,-16]],"0.5"]
            ]
            
            __line.backgroundColor = UIColor(shex:"#aaa")
            contentView.backgroundColor = .clear
            self.backgroundColor = .clear
        }
        override func mo_model_reload() {
            titleL.ui.font16.text(mo.model["title",""])
        }
    }
    
    class Lever2Cell:JoTableCell{
        let titleL = UILabel()
        override func addLayoutRules() {
            contentView.eelay = [
                [titleL,[ee.T.L.B.R,[14,36,-14,-26]],"20"],
            ]
            
            contentView.backgroundColor = .clear
            self.backgroundColor = .clear
        }
        override func mo_model_reload() {
            if mo.model["selected","NO"] == "YES"
            {
                titleL.ui.font15.color(hex: UIColor.main_hex).text(mo.model["title",""])
            }
            else{
                titleL.ui.font14.color(hex: "#555").text(mo.model["title",""])
            }
        }
    }
}





